<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,initial-scale=1.0,width=device-width"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>融云测试</title>
    <link rel="stylesheet" type="text/css" href="./css/api.css" />
    <style type="text/css">
    
    </style>
</head>
<body>
    <div style="margin-top: 30%; margin-left: 15%" tapmode onclick="openchat()">打开聊天窗口</div>
</body>
<script type="text/javascript" src="./script/api.js"></script>
<script type="text/javascript">

	function openchat() {
		api.openWin({
			name : 'chat_win',
			url : 'html/chat_win.html',
			delay : 300
		});
	}
	
	var rong;
    apiready = function(){
	
		//融云2聊天监听模块
		rong = api.require('rongCloud2');
		rongyunListener();
		
		api.addEventListener({
			name : 'reRongCloudConnect'
		}, function(ret, err) {
			if (ret.value.key) {
				rongyunListener();
			}
		});
		
		//获取历史消息
		api.addEventListener({
			name : 'getHistoryMessages'
		}, function(ret, err) {
			if (ret && ret.value) {
				var value = ret.value;
				getHistoryMessages(value.targetId, value.type);
			}
		});
		
		//监听发送消息功能
		api.addEventListener({
			name : 'sendMessage'
		}, function(ret) {
			if (ret && ret.value) {
				var data = ret.value;
				//目标id,消息内容,消息类型
				sendMessage(data.targetId, data.conversationType, data.objectName, data.message);
			}
		});
		
		//断开连接
		api.addEventListener({
			name : 'clearCart'
		}, function(ret, err) {
			if (ret.value.key) {
				disConnect();
			}
		});
    };
    
    function rongyunListener() {
    	//userId = 10001
		//portraitUri = 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png'
		//token = 'tri9RGQkiRqOktPvT30CJblUXq/FwcHLWJ5NfRpLhw5gBWJrTNElV+PNbnsMfYlHajO8vpwOKBYD9rk5rqPuqw==';
		
		//userId = 10002;
		//portraitUri = 'http://img1.360buyimg.com/pop/jfs/t3139/59/4944835986/18414/f3dd2c7c/585cd59cN8736ad36.jpg';
		//token = 'xIF8C5hS8D6OktPvT30CJblUXq/FwcHLWJ5NfRpLhw5gBWJrTNElV63WPo4nG9LMajO8vpwOKBaGm0F8wENiUg==';
		
		//初始化
		init();
		//连接状态
		connectStatus()
		//监听所有信息
		setOnReceiveMessageListener();
		//链接
		connect();
	}
	
	//初始化
	function init() {
		rong.init(function(ret, err) {
			//alert(JSON.stringify(ret));
			if (ret.status == 'error') {
				api.toast({
					msg : err.code
				});
			}
		});
	}
	
	//连接状态
	function connectStatus() {
		rong.setConnectionStatusListener(function(ret, err) {
			
			switch(ret.result.connectionStatus) {
				case ('KICKED'):
					api.alert({
						title : '异常登录',
						msg : '用户账户在其他设备登录,本机会被踢掉线，请修改密码',
						buttons : ['确定']
					}, function(ret, err) {
						if (ret.buttonIndex == 1) {
							api.openWin({
								name : 'forget_win',
								url : 'html/forget_win.html'
							});
						}
					});
					break;
				case ('NETWORK_UNAVAILABLE'):
					api.toast({
						msg : '网络不可用',
						duration : 1000,
						location : 'middle'
					});
					break;
				case ('SERVER_INVALID'):
					api.alert({
						title : '服务器异常',
						msg : '服务器异常或无法连接',
						buttons : ['确定']
					}, function(ret, err) {
					
					});
					break;
			}
		});
	}
	
	//消息的监听，监听到新消息后将消息广播出去，在会话页面监听接收并判断
	function setOnReceiveMessageListener() {
		rong.setOnReceiveMessageListener(function(ret, err) {
			//alert(JSON.stringify(ret));
			if (ret) {
				//alert(ret.result.message.targetId+','+talkingId);
				//将监听到的消息广播出去，在会话页面接收
				api.notification({
					vibrate : [500, 500]
				}, function(ret, err) {
					//alert(ret.id);
				});
				var str = JSON.stringify(ret.result);
				setTimeout(function() {
					api.execScript({
						name : 'chat_win',
						frameName : 'chat_frm',
						script : "getNewMessages('" + str + "')"
					});
				}, 800)
				api.parseTapmode();
			}
		})
	}

	function connect() {
		var token = 'tri9RGQkiRqOktPvT30CJblUXq/FwcHLWJ5NfRpLhw5gBWJrTNElV+PNbnsMfYlHajO8vpwOKBYD9rk5rqPuqw==';
		rong.connect({
			token : '' + token + ''
		}, function(ret, err) {
			if (ret.status == 'success') {
				//api.toast({ msg: ret.result.userId });
			} else {
				//alert(JSON.stringify(err));
				api.toast({ msg: '连接失败' });
			}
		});
	}
	
	
	//发送消息模块
	function sendMessage(targetId, conversationType, objectName, message) {
		//alert(targetId);
		switch(objectName) {
			//文字消息
			case 'RC:TxtMsg':
				rong.sendTextMessage({
					conversationType : conversationType,
					targetId : '' + targetId + '',
					text : message,
					extra : ''
				}, function(ret, err) {
					if (ret.status == 'prepare') {
						var str = JSON.stringify(ret.result);
						api.execScript({
							name : 'chat_win',
							frameName : 'chat_frm',
							script : "backSendMessage('" + str + "')"
						});
					} else if (ret.status == 'success') {
						//发送成功的处理
					} else if (ret.status == 'error') {
						//发送失败的处理
						api.toast({
							msg : err.code
						});
					}
				})
				break;
			//图片消息
			case 'RC:ImgMsg':
				rong.sendImageMessage({
					conversationType : '' + conversationType + '',
					targetId : '' + targetId + '',
					imagePath : message,
					extra : ''
				}, function(ret, err) {
					if (ret.status == 'prepare') {
						var str = JSON.stringify(ret.result);
						api.execScript({
							name : 'chat_win',
							frameName : 'chat_frm',
							script : "backSendMessage('" + str + "')"
						});
					} else if (ret.status == 'progress') {
						//广播图片的进度
					} else if (ret.status == 'success') {
						//发送成功的处理
					} else if (ret.status == 'error') {
						//发送失败的处理
						api.toast({
							msg : err.code
						});
					}
				});
				break;
			//语音消息
			case 'RC:VcMsg':
				rong.sendVoiceMessage({
					conversationType : '' + conversationType + '',
					targetId : '' + targetId + '',
					voicePath : '' + message.path + '',
					duration : Number(message.duration),
					extra : ''
				}, function(ret, err) {
					if (ret.status == 'prepare') {
						var str = JSON.stringify(ret.result);
						api.execScript({
							name : 'chat_win',
							frameName : 'chat_frm',
							script : "backSendMessage('" + str + "')"
						});
					} else if (ret.status == 'success') {
						api.toast({
							msg : ret.result.message.messageId
						});
					} else if (ret.status == 'error') {
						api.toast({
							msg : err.code
						});
					}
				});
				break;
		}
	}

	//获取某一会话的历史消息
	function getHistoryMessages(targetId, type, oldestMessageId) {
		rong.getHistoryMessages({
			conversationType : type,
			targetId : '' + targetId + '',
			oldestMessageId : -1,
			count : 30
		}, function(ret, err) {
			if (ret.status == 'success') {
				//将获得的历史消息广播出去，在会话页面接收
				api.sendEvent({
					name : 'backHistoryMessages',
					extra : {
						message : ret.result
					}
				});
			}
		})
	}

	//断开连接
	function disConnect() {
		rong.disconnect({
			isReceivePush : true
		}, function(ret, err) {
			if ('success' == ret.status) {
				api.toast({
					msg : '断开连接成功!'
				});
			}
		});
	}

</script>
</html>